package com.panda.utils;


import com.panda.pojo.Context;
import com.panda.pojo.Element;

import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class QuoteUtils {

    //处理引用

    private static Pattern qp = Pattern.compile("__element_[a-zA-Z][a-zA-Z0-9]*_[0-9]+");

    static String transformQuote(Context context, Element element, String s) {

        if ("".equals(s)) {
            return s;
        }


        Matcher matcher = qp.matcher(s);

        Set<String> protectedStrings = element.getProtectedStrings();

        while (matcher.find()) {

            Map<String, String> stringMap = context.getStringMap();

            String id = matcher.group(0);

            String js;

            Element re = element;

            while (true) {

                if (re == null || re.isRepetitive()) {
                    break;
                } else {
                    re = re.getParent();
                }

            }

            if (re != null) {

                js = "$($element).children('[eid=" + id + "]')";

            } else {

                //如果没有重复使用的情况下
                js = "$('[eid=" + id + "]')";

            }


            String jsId = IdUtils.create("__js_string_");


            //被保护的脚本并没有被展开

            stringMap.put(jsId, js);

            protectedStrings.add(jsId);

            s = s.replace(matcher.group(), jsId);

        }

        s = s.replaceAll("((?<=([+\\-/*=%!({\\[><&|^;:\n])|^|(in)) *)current((?= *[+-/*=%!()}\\[><?&|^.\n])|$)", "__RDS_CHAR_DOLLAR(__RDS_CHAR_DOLLARelement)");

        s = s.replaceAll("\\?[ \n]*current[ \n]*:", "?__RDS_CHAR_DOLLARelement:");
        s = s.replaceAll("\\?[ \n]*current[ \n]*.", "?__RDS_CHAR_DOLLARelement.");


        return s.replace("__RDS_CHAR_DOLLAR","$");

    }


}
